//Ext.BLANK_IMAGE_URL=CFG.app_ctx+"ext/resources/images/default/s.gif";
var bReadyOk=0;
//var winsvg;
var THLayout = Class(object, {
    Create: function(items){
    	this.version ='2010.12';
    	this.welcome_text="";
        this.items=items;
        this.trees={};
        this.ws = null;
        this.subscribe_cout={};
        this.attach_sid_dom={};
        this.attach_dom_sid={};
        this.verify=false;
        this.pos_left=0;
        this.pos_top=0;
        this.pos_id=0;
        this.mtp={};
        this.close_other_tab=true;   
    },

  send_subscribe:function(cns,action){
	this.ws.send_subscribe(cns,action);
  },
  send:function(data){
  	this.ws.send(data);
  },
  getws:function(url,con_span,cns){
  	if(this.ws){
  		return this.ws;
  	}
	var wsc = New(WSClient,[url,con_span,cns]);
	wsc.setevt("onclose",function(){
		layout.comet_fail();
	});
	wsc.setevt("onopen",function(){
		layout.comet_succ();
	});
	
	wsc.setfunc("PR_SYS_MSG",function(s){
		Bat.msgfmt(s.items.map);
	});
	wsc.setfunc("net.bat.task.Task",function(s){
		var items = s.items.map;
		if(items.fcur){
			Ext.MessageBox.updateProgress(items.fcur, items.info);
		}else{
			if(items.info){
				Ext.MessageBox.updateText(items.info);
			}
			//if(items.title){
			//	Ext.MessageBox.setTitle(items.title);
			//}
		}
	});
	wsc.connect();
	this.ws =wsc;  
	return wsc;
  },
  selectNode:function(treeId,treePath,attr){
  	var tree = this.trees[treeId];
  	if(!tree) return;
  	if(!attr) treePath = "/Root/"+treePath;
  	tree.selectPath(treePath,attr||"text",function(bSuccess, oSelNode ){
  		if(bSuccess) 
  			tree.fireEvent("click",oSelNode);
  	}
  	);
  },
  onEditNotice:function(){
	var wp = Bat.dlgs["edit_notice"];
	if(!wp){
 		
	  var fm = new Ext.Panel({
    items: [{
    	id:'notice_content',
    	width:700,
    	height:250,
        xtype:'htmleditor',
        value:Ext.get("tabs_about").dom.innerHTML
    }]        
	});
    wp = new Ext.Window({
    	modal:true,
     	draggable:false,
    	resizable:false,
   		closeAction:'hide',
    	shadowOffset:15,
    	shadow: true,
        title: '编辑公告',
        width: 716,
        autoHeight:true,
        layout: 'form',
        buttonAlign:'center',
        items: fm,
		defaultButton:'id_ok',
        buttons: [{
        	//id:'id_ok',
            text: '确定',
            handler: function(){
            	var hf = Ext.get('notice_content');
            	var ps = {'notice_content':hf.getValue()};  
             	var req={"map":ps,"javaClass":"java.util.HashMap"};
			  jsonrpc.BH.handle(function(data,ex){
		   		if(Bat.outputEx(ex,'发送留言异常'))
		   			return;
			  	wp.hide();
			  	Ext.get("tabs_about").dom.innerHTML=hf.getValue();
			  layout.tabVersion.bHide=false;
			  layout.tabPanel.unhideTabStripItem(this.tabVersion);
			  layout.tabPanel.setActiveTab(layout.tabVersion.show());
			  },'N',req,'UMService'); 
            }            
        },{
            text: '取消',
            handler: function(){
            	wp.hide();
            }
        }],
        keys: [
        //回车确定
         /*   {stopEvent: true,
			 key: [Ext.EventObject.ENTER], handler: function() {
            	var btn_ok=wp.buttons[0];
            	btn_ok.handler.call(btn_ok.scope || btn_ok, btn_ok); 
               }
            }*/
        ]        
    });
	Bat.dlgs["edit_notice"]=wp;
	}
	wp.show();	
	return false;
  },
  onhelp:function(){
    var tabPanel=this.tabPanel;
   	var hlp_url = CFG.base_url+"hlp/index.htm?kw="+tabPanel.getActiveTab().title;
   	if(!this.tabHelp){
		this.tabHelp= tabPanel.add({
			bodyStyle:'padding:10px;font-size:12px;',
            title: '在线帮助',
            iconCls: 'tabs',
            html: "<iframe style=\"border: 0px;\" width=\"100%\" height=\"100%\" id=\"ifm_hlp\"></iframe>",
           	closable:true,
            autoDestroy: false,
			autoScroll: true,
			bHide:true
        }).show();
       }
   	else{
		 this.tabHelp.bHide=false;
		 tabPanel.unhideTabStripItem(this.tabHelp);
		 tabPanel.setActiveTab(this.tabHelp.show());
   	}
	var ifm = Ext.get("ifm_hlp").dom.src=hlp_url;
	return false;
  },
  login:function(func_succ,user){
	    var loginfm = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 80,
        url:'save-form.php',
        defaultType: 'textfield',
		//defaults: {width: 210},
        items: [{
            xtype:'fieldset',
            autoHeight:true,
            title: '',
             defaultType: 'textfield',
            items:[{
            	fieldLabel:Bat.info.usr_name,
            	mode:'local',
            	name:'user',
            	valueField :'id',
            	value:user||"sys",
            	xtype:'combo',
            	lazyInit:false,
            	emptyText :'请选择',
            	displayField:'name',
            	triggerAction:'all',
            	typeAhead :true,
            	store:{
			        fields: ['id','name'],
			        proxy: {
			           //异步获取数据，这里的URL可以改为任何动态页面，只要返回JSON数据即可
			            type: 'ajax',
			            url: CFG.app_ctx+'servlet/JSonBaseServlet?hql=select userId,name from UUser',
			            
			            reader: {
			                type: 'array',
			                root: 'list'
			            }
			        },
			        autoLoad: false
			    }
            },{
            fieldLabel: Bat.info.usr_pwd,
            name: 'pwd',
           	value: '1',
            inputType: 'password'
        }]}, {
           listeners:{'collapse':function(){loginwin.syncShadow();},'expand':function(){loginwin.syncShadow();}},
            xtype:'fieldset',
            checkboxName:'changepwd',
            checkboxToggle:true,
            title: '修改我的密码',
            //collapsible: true,
            collapsed: true,
            autoHeight:true,
            defaultType: 'textfield',
            //defaults: {width: 210},
            items :[{
                    fieldLabel: '新密码',
                    name: 'pwd1',
                    inputType: 'password',
                    value: ''
                },{
                    fieldLabel: '确认新密码',
                    inputType: 'password',
                    name: 'pwd2',
                   	validator:function(val){
                   	  	if(val==loginfm.getForm().findField('pwd1').getValue())
		            	  return true;
		            	else  return '密码输入不一致';  
		            }	                                
                }
             ]
        }]        
    });
    //form.render(document.body);
	//return;
    var loginwin = new Ext.Window({
    	draggable:false,
    	resizable:false,
    	//monitorResize:true,
    	shadowOffset:15,
    	shadow: true,
   		//modal:true,
    	closable:false,
        title: '登录',
        width: 350,
        //height:200,
        autoHeight:true,
        layout: 'auto',
        plain:true,
        //bodyStyle:'padding:5px;background-image:url("icons/bg_login.png");',
        buttonAlign:'center',
        items: loginfm,
		defaultButton:'login_id_ok',
        buttons: [{
        	id:'login_id_ok',
            text: '确定',
            handler: function(){
            	this.disable();
            	loginwin.setTitle("正在登录,请稍等...");
            	var ps = loginfm.getForm().getValues();
            	if(ps.changepwd){ 
            		if(ps.pwd1!= ps.pwd2)
            	 		return false;
            	}else{
            		delete ps.pwd1;
            		delete ps.pwd2;
            	}
            	//Bat.gvs.wf_userName=ps.user;
            	ps.user =  loginfm.getForm().findField('user').getValue();
            	var req={"map":ps,"javaClass":"java.util.HashMap"};
			  jsonrpc.BH.handle(function(data,ex){
		   		if(Bat.outputEx(ex,'用户登录异常')){
		   			loginwin.setTitle("登录失败,请检查用户名密码");
            		loginwin.down('button').enable();
		   			return;
		   		}
		   		//TODO 根据获得的菜单权限组织菜单
		   		if(data!=null){
		   			//layout.welcome_text="<b>"+data[0]+"-"+ps.user+"</b>&nbsp;&nbsp;&lt;"+(new Date()).toLocaleString()+"登录&gt;";
		   			layout.welcome_text="<span style=\"color:white;\">欢迎您,<img src=\"icons/user.png\"></img><b>"+data[3]+"</b>&nbsp;&nbsp;&nbsp;</span>";
		   			layout.usr_info=ps;
		   			layout.usr_grant=data;
		   			layout.uid=data[4];
		   			loginwin.hide(); 
					func_succ(data);
		   		}
			  },'L',req,'UMService');            	
            }            
        }/*,{
            text: '取消',
            handler: function(){
            	loginwin.hide();
            }
        }*/],
		keys: [
            {stopEvent: true,
			 key: [Ext.EventObject.ENTER], handler: function() {
            	var btn_ok=loginwin.buttons[0];
            	btn_ok.handler.call(btn_ok.scope || btn_ok, btn_ok); 
               }
            }
        ]        
    });

    loginwin.show();
    
  	if(user){
  		var btn_ok=loginwin.buttons[0];
        btn_ok.handler.call(btn_ok.scope || btn_ok, btn_ok);   		
  	}
  },
  dowithState:function(s){
  	if(s.cn=="Task")
  	  Bat.showProgress(s);
  	if(s.cn=="MMessage" && s.action=='A' ){
  	 	var pm = s.items.map;
  	 	if(pm && pm.stype!='SYS_RECOVER')
  	 		Bat.msgfmt(pm);
  	}
  	//if(s.cn=="MHeart")
  	//	alert(s.items.map.tm.time);
  },
  addTask:function(s){
  	
  },
  updateTask:function(s){
  	
  },
  removeTask:function(s){
  	
  },
  comet_succ:function(e){
  	if(layout.verify){
	  var req={"map":{handleKey:layout.usr_grant[2]},"javaClass":"java.util.HashMap"};
	  jsonrpc.BH.handle(function(data,ex){
   		if(data[0]==0 && !ex){
   			ex={msg:'会话已失效，请重新登录'};
   		}
   		if(Bat.outputEx(ex,'恢复登录失败'))
   			return;
	  },'V',req,'UMService');            	 		
  	}
  	if(Ext.MessageBox.isVisible())
  		Ext.MessageBox.hide();
  	var mi = this.tbar.queryById("mi_comet");
  	mi.setText("已连接");
  	mi.setIconCls("link");  	
  },
  comet_connect:function(e){
  	var mi = this.tbar.queryById("mi_comet");
  	mi.setText("连接中");
  	mi.setIconCls("link");
  },
  comet_fail:function(e){
  	var mi = this.tbar.queryById("mi_comet");
  	mi.setText("未连接");
  	mi.setIconCls("link_break");
  	this.verify=true;
    Ext.MessageBox.alert({
       title: '连接服务失败',
       msg: '由于网络繁忙或服务关闭,暂无服务响应。<br>您可以关闭浏览器并稍后尝试重新连接,<br>或者保持目前界面并等待服务恢复。'
   });
  },
  /**
   * 根据vn,kn,kv直接打开并渲染详细页
   * @param {} vn
   * @param {} kn
   * @param {} kv
   */
  renderDetailByKey:function(vn,kn,kv){
  	//TODO 复用
  	var vwd = BView.viewMap[vn];
  	var vw = New(BView,[vwd]);
	vw.req.map.method = 'G';
	var kn=kn||'id';
	if(vw.req.map.cns.length>1){
		kn='A.'+kn;
	}
	var hql = vw.req.map.hql;
	var pos_ordby = hql.toLowerCase().indexOf('order by');
	if(pos_ordby!=-1){
		hql = hql.substring(0,pos_ordby);
	}
	var pos = hql.toLowerCase().indexOf('where');
	if(pos==-1){
		 vw.req.map.hql=hql+' where '+kn+'='+kv;
	}else{
		 vw.req.map.hql=hql+' and '+kn+'='+kv;
	}
	
	jsonrpc.BH.handle(function(data, ex) {
		if (Bat.outputEx(ex, '请求记录数据异常'))
			return;
			var obj;
			if(data.length>1){
			 	obj = data[1];
			}else{
				obj = data[0];
			}
			if(vwd.func_item){
				vwd.func_item(vw,obj);
			}
			var bui = vwd.bui;
			if(!bui){
				bui=New(BatUI,[vw,layout.tabPanel,vwd.cn||vn]);
				vwd.bui=bui;
			}
			Bat.setIts(obj);
			bui.renderDetailPanel(obj);
		}, 'G', vw.req, '');
  },
  renderGridByNode:function(node){
	var vn=node.vn||node.get('vn');	
	if(!vn){
		return;
	}
	var bui = node.bui;
	if(!bui){
		var vw = New(BView,[BView.viewMap[vn]]);
		if(node.nc.func_vw)
			node.nc.func_vw(vw);
		var title = node.getPath('text').substr(6);
		bui = New(BatUI,[vw,this.tabPanel,title]);
		var cd = this.tabPanel.add({
			title : title,
			closable : true,
			autoDestroy : false,
			autoScroll : false,
			layout:'fit',
			items: {
			    title: 'Fit Panel',
			    header:false,
			    xtype:'bat_grid',
			    border: false,
			    ui:bui
			}
		});
		cd.show();
		bui.tabGrid = cd;		
		node.bui = bui;
	}
	bui.renderGridTab();
  },    
    
  buildNode:function(pn,nc){
	if(!pn || !nc)
	  return;	
	if(typeof nc=='string')
	  nc = {text:nc};
	var cn = pn.appendChild(nc);
  	cn.nc=nc;
  	cn.vn=nc.vn;
	if(nc.ns){
		for(var i=0; i<nc.ns.length; i++){
			this.buildNode(cn,nc.ns[i]);
		}  	
	}else{
		cn.set('leaf',true);
	}
	return cn;
  },
  buildTree:function(nn,id,title,iconCls,func_click){
	var root = {
		text:"Root", 
		allowDrag:false,
		allowDrop:false
	};
   var tree = new Ext.tree.Panel( {
		id:id,
		markDirty :false,
		useArrows: true,
		title:title,
		iconCls:iconCls,
		root:root,
		animate:true, 
		containerScroll: true,
		rootVisible:false
	});
	for(var i=0;i<nn.length;i++)
	  	this.buildNode(tree.getRootNode(),nn[i]);
	if(func_click)
		tree.on("click",func_click,this);
	else{
	  //var me=this;
	  tree.on('itemclick',function(self, store_record, html_element, node_index, event){
		  if(this.close_other_tab){
			  var items = [];
		        this.tabPanel.items.each(function(item){
		        	
		            if(item.closable){
		                if(!false|| item != this.item){
			                items.push(item);        
		                }
		            }

		        }, this);
		        
			 Ext.each(items, function(item){
				    
		            this.tabPanel.remove(item);
		            
		     }, this);
			 
	 }
		this.renderGridByNode(store_record);		
	},this);
	}
	//tree.expandAll();
	this.trees[id]=tree;
	tree.expandAll();
	return tree;
  },
 buildToolbar:function(){
 	var svs=[];
 	for(var i=10; i<100; i+=5){
 		svs[svs.length]=[i+"",i];
 	}
    var combo = new Ext.form.ComboBox({
        hideLabel: true,
        store: new Ext.data.SimpleStore({
			fields : ['txt', 'val'],
			data :svs
		}),
		displayField : 'txt',
		valueField : 'val',
		typeAhead : true,
		mode : 'local',
		triggerAction : 'all',
		emptyText : 'Top...',
		selectOnFocus : true,
		width:100,
		value:gridPagePer,
		listeners:{
		  scope:this,
         'select': function(co,rec,index){
        	gridPagePer=co.getValue();
         }
    	}
    });
		var ths=["classic","gray","access","neptune"];
		var thsItems=[];
		for(var i=0; i<ths.length; i++){
			thsItems[thsItems.length]={checked: false,text:ths[i],group:"theme",
				checkHandler:function(item, checked){
					if(checked){
						//var name = select[select.selectedIndex].value;
        				setActiveStyleSheet(item.text);
        				
					}
				}
		  }
		}
		var bk_url = CFG.base_url+"th/icons/head.jpg";
            
		return {
		style: 'padding-top:15px;padding-right:150px;background-color: #094AB2;', 
	 	region:'north',
	 	height: 40,
	 	id:'toolbar-left',
	 	items:[
		'->',
		this.welcome_text,
		{
		    text:'选项',
         	cls: 'x-btn-text-icon',
         	icon: 'icons/opt.png',
            menu: {
			items: [combo,
				{ text: '主题风格',
                icon: 'icons/style.png',                
                menu: {        // <-- submenu by nested config object
                    items:thsItems
                }
            },
            { text:'在线帮助',
			 icon: 'icons/book_open.png',
				handler:function(btn){
					return layout.onhelp();
			  },scope:this
            },{				
			 text:'公告栏',
			 icon: 'icons/star.png',
				handler:function(btn){
					if(layout.usr_grant[0]=="admin"){
						return layout.onEditNotice();
					}
				  this.tabVersion.bHide=false;
				  //this.tabPanel.unhideTabStripItem(this.tabVersion);
				  this.tabVersion.tab.show()
				  this.tabPanel.setActiveTab(this.tabVersion);
			  },scope:this
			},{				
			 text:'状态图',
			 icon: 'icons/asterisk_orange.png',
				handler:function(btn){
				 BView.openTabpanel("arbor","发布-订阅状态图","../ol/arbor.html");
			  },scope:this
			},
			{text:'关于',
			 id:'mi_about',
			 icon: 'icons/information.png',
				handler:function(){Ext.MessageBox.show({
				title:'关于', 
				icon: Ext.MessageBox.INFO,
				animEl:'mi_about',
				msg:'<p align=\'center\'>'+CFG.app_name+CFG.about+'</p>',
				buttons: Ext.MessageBox.OK,
				width:220
			});
			}			
			}]}},
			{
				id:"mi_comet",
				disabled:true,
				 text:'未连接',
				 iconCls: 'link_break',
				 handler:function(btn){
				 	Bat.comet.setconnect(false);
				 	var mi = this.tbar.findById("mi_comet");
	  				mi.setText("未连接");
					mi.setIconClass("link_break");
				  },scope:this
				},
	 	{
		 id:'mi_exit',
         cls: 'x-btn-text-icon',
         icon: 'icons/quit.png',
		 text:'注销',
		 handler:function(){
		 	Ext.MessageBox.confirm("退出确认","您确定要退出系统吗？",function(btn){
		 		if(btn=="no")
		 			return;
			  var req={"map":layout.usr_info,"javaClass":"java.util.HashMap"};
			  jsonrpc.BH.handle(function(data,ex){
		   		if(Bat.outputEx(ex,'用户退出异常'))
		   			return;
		   		location.reload(true);
			  },'O',req,'UMService');            	
		 	});
		 }
		},	{
		 id:'mi_save',
         cls: 'x-btn-text-icon',
         icon: 'icons/disk.png',
		 text:'保存',
		 hidden:true,
		 //scope:this,
		 handler:function(b,e){
		 	var tp = layout.tabPanel;
		 	var ap = tp.getActiveTab();
		 	var uidt = ap.uiDetail;
		 	//110111 "this" change after remove ap
		 	tp.remove(ap,false);
		 	//this.tabPanel.hideTabStripItem(ap);
		 	//ap.hide();
	 		uidt.save();
		 	if(uidt.pui){
		 		tp.setActiveTab(uidt.pui.tabDetail);
		 	}else tp.setActiveTab(uidt.tabGrid);
		}
		},{
		 id:'mi_next',
         cls: 'x-btn-text-icon',
         icon: 'icons/arrow-down.gif',
		 text:'向前',
		 hidden:true,
		 //scope:this,
		 handler:function(b,e){
		 	var tb = layout.tbar;
		 	var tp = layout.tabPanel;
		 	var ap = tp.getActiveTab();
		 	var ui = ap.uiDetail;
		 	var objs = ui.objs;
		 
		 	var objcur=ui.obj_detail;
		 	var len = objs.length;
		 	for(var i=0; i<len; i++){
		 		if(objcur==objs[i]){
		 			if(i<len-1){
		 				ui.setObjDetail(objs[i+1]);
		 			}
		 			if(i==len-2){
		 				tb.get("mi_next").disable();
		 			}
		 			tb.get("mi_prev").enable();
		 			break;
		 		}
		 	}		 	
		}
		},{
		 id:'mi_prev',
         cls: 'x-btn-text-icon',
         icon: 'icons/arrow-up.gif',
		 text:'向后',
		 hidden:true,
		 //scope:this,
		 handler:function(b,e){
		 	var tp = layout.tabPanel;
		 	var ap = tp.getActiveTab();
		 	var ui = ap.uiDetail;
		 	var objs = ui.objs;
		 	var objcur=ui.obj_detail;
		 	var len = objs.length;
		 	for(var i=0; i<len; i++){
		 		if(objcur==objs[i]){
		 			if(i>0){
		 				ui.setObjDetail(objs[i-1]);
		 			}
		 			if(i==0){
		 				tb.get("mi_prev").disable();
		 			}
		 			tb.get("mi_next").enable();
		 			break;
		 		}
		 	}		 	
		}
		}]};
	},
	hideDetailBtns:function(){
		var its_tbar = this.tbar.items;
		for(var i=5; i<its_tbar.length; i++){
			var ci = its_tbar.items[i];
			//避免删除右边栏
			if(ci.btnEl)
				ci.hide();
		}
	},
	attachDom:function(sid,domId){
		var old_sid = this.attach_dom_sid[domId];
		if(old_sid){
			//原来sid数组无效
			delete this.attach_sid_dom[old_sid];
			this.getAttachDom(old_sid);
		}
		this.attach_dom_sid[domId]=sid;
		//新sid数组也无效
		delete this.attach_sid_dom[sid]
		this.getAttachDom(sid);
		return domId;
	},
	getAttachDom:function(sid){
		var domIds = this.attach_sid_dom[sid];
		if(domIds){
			return domIds;
		}else{
			var dids = [];
			for(x in this.attach_dom_sid){
				if(this.attach_dom_sid[x]==sid){
					dids[dids.length]=x;
				}
			}
			this.attach_sid_dom[sid]=dids;
			return dids;
		}
	},
	show_subscribe:function(prs){
		var prs_send=[];
		for(var i=0; i<prs.length; i++){
			var pr = prs[i];
			var pr_count=this.subscribe_cout[pr];
			if(!pr_count){
				this.subscribe_cout[pr] =1;
				prs_send[prs_send.length]=pr;
			}else{
				this.subscribe_cout[pr] = pr_count++;
			}			
		}
		if(prs_send.length>0){
			this.send_subscribe(prs_send,'A');
		}
	},
	hide_subscribe:function(prs){
		if(!prs){
			return false;
		}
		var prs_send=[];
		for(var i=0; i<prs.length; i++){
			var pr = prs[i];
			var pr_count=this.subscribe_cout[pr];
			if(!pr_count){
				this.subscribe_cout[pr] = pr_count--;
				if(this.subscribe_cout[pr]==0){
					prs_send[prs_send.length]=pr;
				}
			}			
		}
		if(prs_send.length>0){
			this.send_subscribe(prs_send,'R');
		}
	},
	show:function(){
       var tabPanel=new Ext.TabPanel({
       		autoDestroy:false,
        	tps:[],
        	show_tabs:{},
            region:'center',
            id:'center',
            enableTabScroll:true,//wjh
            defaults: {autoScroll:true},//wjh                    
            deferredRender:false,
            plugins: new Ext.ux.TabCloseMenu(),
           listeners:{
            "contextmenu":function(tabs,tab,e){
              tabs.tabmenu=tab;
              var menu = tabPanel.cmenu;
              if(!menu){
				menu=new Ext.menu.Menu({items:[{
				text:"关闭其他页",
				handler:function(){
					tabs.setActiveTab(tabs.tabmenu);
					//循环遍历
					tabs.items.each(function(item){
					if(item!=tabs.tabmenu){
				        tabs.hideTabStripItem(item.hide());
				        item.bHide=true;
					}
					});
				 }
				},{
				text:"关闭所有页",
				handler:function(){
					//循环遍历
					tabs.items.each(function(item){
				        tabs.hideTabStripItem(item.hide());
				        item.bHide=true;
					});
				 }
				}]});
				tabPanel.cmenu=menu;
              }
				//显示在当前位置
				menu.showAt(e.getPoint()); 
			  }
            }
        });
       this.tabPanel=tabPanel;
       tabPanel.on('add', function(tabs, tab) {
       		if(tabs.tps)
       	 		tabs.tps[tabs.tps.length]=tab;
       	 	else
       	 		tabs.tps=[];
		});	
       tabPanel.on('beforeremove', function(tabs, tab) {
	        //tabs.hideTabStripItem(tab.hide());
       		tab.tab.hide();
	        layout.hide_subscribe(tab.prs);
	        tab.bHide=true;
	        //关闭当前页
	        if(tab==tabs.getActiveTab()){
	        	for(var i=tabs.tps.length-1; i>=0; i--){
	        		var tc = tabs.tps[i];
	        		if(!tc.bHide){
	        			tabs.setActiveTab(tc.show());
	        			break;
	        		}
	        	}
	        }
	        return false;
		});	
		var tbar = new Ext.Toolbar(this.buildToolbar());     
		this.tbar = tbar;
        var viewport = new Ext.Viewport({
            layout: 'border',
            items: [
				tbar,{
                region: 'west',
                id: 'west-panel', // see Ext.getCmp() below
                title: '功能导航',
                split: true,
                width: 200,
                minSize: 175,
                maxSize: 400,
                collapsible: true,
                margins: '0 0 0 5',
                layout: {
                    type: 'accordion',
                    animate: true
                },
                items:this.items
            },tabPanel
            ]
        });
        this.viewport = viewport;

		this.tabVersion= tabPanel.add({
			bodyStyle:'padding:10px;font-size:12px;',
            title: '公告栏',
            iconCls: 'tabs',
            contentEl: 'tabs_about',
           	closable:true,
            autoDestroy: false,
			autoScroll: true		
        }).show();
     }
});


var layout;
var grant_opts=[["无",0],["全部",1]];

Ext.onReady(function(){
	

	document.title=CFG.app_name;
	Ext.QuickTips.init();
// Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
	jsonrpc = new JSONRpcClient(CFG.app_ctx+"JSON-RPC");
	var its =  [ {
        title: '用户管理',
        html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'group'
    },{
        title: '监控管理',
        html: '<p>Some settings in here.</p>',
        border: true,
        iconCls: 'wrench_orange'
    },{
        title: '统计报表',
        html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'chart_bar'
    },{
        title: '在线留言',
        html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'page_edit'
    },{
        title: '内容管理',
        html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'group'
    },{
        title: '项目管理',
        html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'group'
    },{
    	title:'藏品征集',
    	html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'group'
    },{
    	title:'藏品登编',
    	html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'group'
    },{
    	title:'动态管理',
    	html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'group'
    },{
    	title:'账目管理',
    	html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'group'
    },{
    	title:'鉴定信息管理',
    	html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'group'
    },{
    	title:'开发调试',
    	html: '<p>Some settings in here.</p>',
        border: false,
        iconCls: 'group'
    }];
	for(var i=0; i<its.length; i++){
		grant_opts[grant_opts.length]=[its[i].title,grant_opts.length];
	}
   var its_grant=[]; 
   layout = New(THLayout,[its_grant]);
var func_succ=function(grants){
   //将功能菜单项灌到授权视图选项中
	var vw_grant=BView.viewMap["dao.hb.UGrant"];
	var cfg_prop_menu=vw_grant.cfg_prop["pmMenu"];
	cfg_prop_menu.cfg=BView.func_cfg_combo(grant_opts);
	cfg_prop_menu.renderer =function(val) {		
		if(grant_opts[val])
			return grant_opts[val][0];
		else
			return "";
	};
	var func_grants=function(gts,mnu){
		if(gts==null)
		  return false;
		if(gts[0]=="DEV")
		  return true;
		  //grants[5+]: menu grants
		for(var i=5; i<gts.length; i++){
			if(gts[i]=="1"||gts[i]==mnu)
			  return true;
		}
		return false;
	}

/*  if(func_grants(grants,"6")){
	   var nn_3=[{
			text:"我的餐馆",
			qtip:"我的餐馆",
			vn:"dao.hb.NBase",
			func_vw:function(vw){
				vw.req.map.hql="from NBase where itype=1 and uid="+layout.uid;
				vw.func_setdefault=function(robj,objs){
					objs[0].items.map["itype"]=1;
				}
				vw.cfg_grid.btns=['增加','删除','打开','保存','检索','刷新','排序',BView.btns["json"]];
			}},{
			text:"他的餐馆",
			qtip:"他的餐馆",
			vn:"dao.hb.NBase",
			func_vw:function(vw){
				vw.req.map.hql="from NBase where itype=1 and uid=1";
				vw.func_setdefault=function(robj,objs){
					objs[0].items.map["itype"]=1;
				}
			}}];
		its_grant[its_grant.length]=layout.buildTree(nn_3,"itr_6","内容管理",'page_edit');
	  }
*/
	/**
	if(func_grants(grants,"7")){
	   var nn_3=[{
			text:"项目",
			qtip:"项目",
			vn:"dao.hb.PProject",
			ns:[{
				text:'按类型',
				ns:[{
					text:'外派',
					vn:"dao.hb.PProject",func_vw:function(vw){
						vw.req.map.hql="from PProject where stype='外派' order by id desc";
					}
				},{
					text:'合同',
					vn:"dao.hb.PProject",func_vw:function(vw){
						vw.req.map.hql="from PProject where stype='合同' order by id desc";
					}
				}
				]
			},{
				text:'按阶段'	,
				ns:[{
					text:'需求调研',
					vn:"dao.hb.PProject",func_vw:function(vw){
						vw.req.map.hql="from PProject where status='需求调研' order by id desc";
					}

				},{
					text:'部署',
					vn:"dao.hb.PProject",func_vw:function(vw){
						vw.req.map.hql="from PProject where status='部署' order by id desc";
					}
				}
				]			
			}
			]
			},{
			text:"任务",
			qtip:"任务",
			vn:"dao.hb.PTask",
			ns:[{
				text:"已建任务",
				qtip:"已建任务",
				vn:"dao.hb.PTask1",func_vw:function(vw){
						vw.req.map.hql="from PTask where uid="+layout.uid+" order by id desc";
					}
				},{
				text:"我的任务",
				qtip:"我的任务",
				vn:"dao.hb.PTask",func_vw:function(vw){
						vw.req.map.hql="from PTask where aid="+layout.uid+" order by id desc";
					}
				},{
				text:"待决任务",
				qtip:"待决任务",
				vn:"dao.hb.PTask",func_vw:function(vw){
						vw.req.map.hql="from PTask where aid is null order by id desc";
					}
				}]
			},{
			text:"活动日志",
			qtip:"活动日志",
			vn:"dao.hb.LSync"
			}
		];
		its_grant[its_grant.length]=layout.buildTree(nn_3,"itr_7","项目管理",'page_edit');
	  }
	  
	if(func_grants(grants,"3")){
	   var nn_0=[{
			text:"地理位置",
			qtip:'地理位置',
			vn:"dao.hb.OLocation"
			},{
			text:"设备类型",
			qtip:"设备类型",
			vn:"dao.hb.ODeviceType"
			},{
			text:"全部设备",
			qtip:"全部设备",
			vn:"dao.hb.ODevice"
			},{
			text:"附件管理",
			qtip:"附件管理",
			vn:"dao.hb.OAttachment"
			}];
	   its_grant[its_grant.length]=layout.buildTree(nn_0,"itr_0","监控管理",'wrench_orange');
	  }
	
	
  if(func_grants(grants,"2")){
   var nn_1=[{
		text:"用户",
		qtip:"用户",
		vn:"dao.hb.UUser",func_vw:function(vw){
			vw.cfg_grid.btns=['增加','删除','打开','保存','检索','刷新','排序'];
			vw.cfg_detail.btns=['保存'];
		}},{
		text:"组织机构",
		qtip:"组织机构",
		vn:"dao.hb.UOrg"},{
		text:"用户组",
		qtip:"用户组",
		vn:"dao.hb.UGroup"},{
			text:"总账",
			qtip:"总账",
			vn:"dao.hb.Bm"
		}];
	its_grant[its_grant.length]=layout.buildTree(nn_1,"itr_1","用户管理",'group');
  }  **/
  if(func_grants(grants,"4")){
	   var nn_5=[{text:"报警统计",qtip:"报警统计",icon:"icons/chart_pie.png",vn:"dao.hb.LAlarm"}];
	   its_grant[its_grant.length]=layout.buildTree(nn_5,"itr_5","统计报表",'chart_bar',null,function(node,e){
	   	var tabPanel=this.tabPanel;
	   	if(!this.tabSta){
			this.tabSta= tabPanel.add({
				bodyStyle:'padding:10px;font-size:12px;',
	            title: '统计报表',
	            iconCls: 'tabs',
	            html: "<iframe style=\"border: 0px;\" width=\"100%\" height=\"100%\" id=\"ifm_sta\"></iframe>",
	           	closable:true,
	            autoDestroy: false,
				autoScroll: true,
				bHide:true
	        }).show();
	       }
	   	else{
			 this.tabSta.bHide=false;
			 tabPanel.unhideTabStripItem(this.tabSta);
			 tabPanel.setActiveTab(this.tabSta.show());
	   	}
	   	 var chart={"饼状图":"sample_pie","柱状图":"sample_bar","折线图":"sample_line","监控图":"realMap"};
		 var nn = node.getPath('text').substr(6);
		 var ifm = Ext.get("ifm_sta").dom.src="svg/"+chart[nn]+".svg";
	   });
	  }
  /**
  if(func_grants(grants,"5")){
	   var nn_2=[{
			text:"发留言",
			qtip:"发留言",
			vn:"dao.hb.UUser"},	{
			text:"已发送",
			qtip:"已发送",
			vn:"dao.hb.MMessage"},{
			text:"待处理",
			qtip:"待处理",
			vn:"dao.hb.MInbox",
			func_vw:function(vw){
				vw.req.map.hql="from MInbox A, MMessage B where A.mid=B.id and B.tmReply is null order by A.id desc";
			}},{
			text:"已处理",
			qtip:"已处理",
			vn:"dao.hb.MInbox",
			func_vw:function(vw){
				vw.req.map.hql="from MInbox A, MMessage B where A.mid=B.id and B.tmReply is not null order by A.id desc";
			}}];
		its_grant[its_grant.length]=layout.buildTree(nn_2,"itr_2","留言",'page_edit');
	  }**/
  if(func_grants(grants,"8")){
	   var nn_2=[{
			text:"藏品编目",
			qtip:"藏品编目",
			icon : '../ipc/icons/fam/comment_edit.png',
			vn:"dao.hb.Bm"},{
				text:"藏品完残",
				qtip:"藏品完残",
				icon:'../ipc/icons/fam/folder_go.png',
				vn:"dao.hb.BmWc"}];
		its_grant[its_grant.length]=layout.buildTree(nn_2,"itr_8","藏品征集",'page_edit');
	  }
  if(func_grants(grants,"9")){
	   var nn_2=[{
			text:"藏品编目",
			qtip:"藏品编目",
			icon : '../ipc/icons/fam/comment_edit.png',
			vn:"dao.hb.Bm"},{
				text:"藏品完残",
				qtip:"藏品完残",
				icon:'../ipc/icons/fam/folder_go.png',
				vn:"dao.hb.BmWc"}];
		its_grant[its_grant.length]=layout.buildTree(nn_2,"itr_9","藏品登编",'page_edit');
	  }
  if(func_grants(grants,"10")){
	   var nn_2=[{
			text:"藏品编目",
			qtip:"藏品编目",
			icon : '../ipc/icons/fam/comment_edit.png',
			vn:"dao.hb.Bm"},{
				text:"藏品完残",
				qtip:"藏品完残",
				icon:'../ipc/icons/fam/folder_go.png',
				vn:"dao.hb.BmWc"}];
		its_grant[its_grant.length]=layout.buildTree(nn_2,"itr_10","动态管理",'page_edit');
	  }
  if(func_grants(grants,"11")){
	   var nn_2=[{
			text:"藏品编目",
			qtip:"藏品编目",
			icon : '../ipc/icons/fam/comment_edit.png',
			vn:"dao.hb.Bm"},{
				text:"藏品完残",
				qtip:"藏品完残",
				icon:'../ipc/icons/fam/folder_go.png',
				vn:"dao.hb.BmWc"}];
		its_grant[its_grant.length]=layout.buildTree(nn_2,"itr_11","帐目管理",'page_edit');
	  }
  if(func_grants(grants,"12")){
	   var nn_2=[{
			text:"藏品编目",
			qtip:"藏品编目",
			icon : '../ipc/icons/fam/comment_edit.png',
			vn:"dao.hb.Bm"}];
		its_grant[its_grant.length]=layout.buildTree(nn_2,"itr_12","鉴定管理",'page_edit');
	  }
  if(func_grants(grants,"9")){
	   var nn_2=[{
			text:"藏品编目",
			qtip:"藏品编目",
			vn:"dao.hb.Bm"},{
				text:"藏品完残",
				qtip:"藏品完残",
				vn:"dao.hb.BmWc"},{
					text:"藏品方位",
					qtip:"藏品方位",
					vn:"dao.hb.BmFw"
				},{
					text:"出入库单据",
					qtip:"出入库单据",
					vn:"dao.hb.BmCrk"
				},{
					text:"出入库藏品",
					qtip:"出入库藏品",
					vn:"dao.hb.BmCrkCp"
				},{
					text:"鉴定藏品",
					qtip:"鉴定藏品",
					vn:"dao.hb.BmJdCp"
				},{
					text:"鉴定专家表",
					qtip:"鉴定专家表",
					vn:"dao.hb.BmJdzj"
				},{
					text:"藏品事故信息表",
					qtip:"藏品事故信息表",
					vn:"dao.hb.BmSg"
				},{
					text:"藏品修复信息",
					qtip:"藏品修复信息",
					vn:"dao.hb.BmXf"
				},{
					text:"鉴定单据",
					qtip:"鉴定单据",
					vn:"dao.hb.BmJd"
				}];
		its_grant[its_grant.length]=layout.buildTree(nn_2,"itr_13","开发调试",'page_edit');
	  }
   layout.show();
   Bat.init(layout);
   
 //直接关闭浏览器时通知服务注销
// beforeunload unload
 Ext.EventManager.on(window, 'beforeunload', function(){
  Ext.MessageBox.wait('正在注销，请稍候...');
  var req={"map":layout.usr_info,"javaClass":"java.util.HashMap"};
  //此处必须用同步方式请求
  var data =  jsonrpc.BH.handle('O',req,'UMService');
  Bat.close_win_all();
   Ext.MessageBox.hide();
 }
 ); 
 
 bReadyOk=1;
 
  }
 
  //分析url是否包含测试信息
  var para = decodeURIComponent(window.location.search);
  var pos_user = para.indexOf("user=")
  if(pos_user!=-1){
  	var userId = para.substring(pos_user+5);
  	layout.login(func_succ,userId);
  }
  else  
    layout.login(func_succ);
});

//处理键盘消息
if ('onhelp' in window) {   // Internet Explorer
    window.onhelp = function(){
   		 return layout.onhelp();
    };
}
else {  // Firefox, Opera, Google Chrome and Safari
    window.onkeydown = OnKeyDown;
}


function OnKeyDown (event) {
    if (event.keyCode == 112 /*KeyboardEvent.DOM_VK_F1*/) {
        return layout.onhelp();
    }
}
